package com.ridanlabs.professorwebsite.controller;

import java.util.EnumSet;
import java.util.Set;
import javax.validation.Valid;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ridanlabs.professorwebsite.general.*;
import com.ridanlabs.professorwebsite.models.DAO;
import com.ridanlabs.professorwebsite.models.UserProfile;
import com.ridanlabs.professorwebsite.security.*;

@Controller
@PreAuthorize("hasAuthority('NEW_USER')")
@RequestMapping(value="/register")
public class RegistrationController {

    @RequestMapping(method= RequestMethod.GET)
    public RegistrationForm registrationForm() {
    	RegistrationForm  registrationForm = new RegistrationForm();
    	registrationForm.setUserType("Student");
        return new RegistrationForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String register(@Valid RegistrationForm form, BindingResult result) {
    	if( result.hasErrors() ) return null; //if Binding to modal had errors, show errors
    	
    	DAO dao = new DAO();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserProfile userProfile = (UserProfile)authentication.getPrincipal();
        
        Set<Authority> authorities = EnumSet.noneOf( Authority.class );
        authorities.add( Authority.fromString(form.getUserType()) );
        authorities.add( Authority.USER ); 
        
        userProfile.setAuthorities( authorities );
        userProfile.setFirstName( form.getForename() );
        userProfile.setLastName( form.getSurname() );
        userProfile.setSchoolId( form.getSchoolId() );

        dao.saveUserProfile(userProfile);

        // Update the context with the full authentication
        SecurityContextHolder.getContext().setAuthentication(new UserProfileAuthentication(userProfile, authentication.getDetails()));

        return "redirect:/home";
    }
}
